package com.juyu.miliao.api.service;

import com.juyu.miliao.api.dao.elasticsearch.FindDynamicElasticsearch;
import com.juyu.miliao.api.dao.mysql.FindDynamicInfoDao;
import com.juyu.miliao.api.dao.mysql.FindDynamicLikeDao;
import com.juyu.miliao.api.dao.redis.FindDynamicLikeDaoRedis;
import com.juyu.miliao.api.domain.FindDynamicLikeInfo;
import com.juyu.miliao.api.domain.vo.FindDynamicLikeVO;
import com.juyu.miliao.api.handler.IntegralRewardsAndPunishmentsHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

/**
 * 发送点赞Service
 * @author xuanqicheng
 */
@Service
public class FindDynamicLikeService {

    @Autowired
    private FindDynamicLikeDao findDynamicLikeDao;

    @Autowired
    private FindDynamicLikeDaoRedis findDynamicLikeDaoRedis;

    @Autowired
    private FindDynamicInfoDao findDynamicInfoDao;

    @Autowired
    private FindDynamicElasticsearch findDynamicElasticsearch;

    @Autowired
    private IntegralRewardsAndPunishmentsHandler integralRewardsAndPunishmentsHandler;

    /**
     * 点赞
     * @param userId
     * @param findId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public FindDynamicLikeVO addFindDynamicLikeInfo(long userId, int findId) throws IOException {
        FindDynamicLikeInfo query = new FindDynamicLikeInfo();
        query.setFindId(findId);
        query.setUserId(userId);
        FindDynamicLikeInfo findDynamicLikeInfo=findDynamicLikeDao.selectInfoByUserIdAndFindId(query);
        if(findDynamicLikeInfo!=null){
            int num=findDynamicLikeDaoRedis.deleteDynamicLike(findDynamicLikeInfo);
            if(num ==1){
                //修改
                int updateNum=findDynamicInfoDao.subtractionLikeNumber(findId);
                if(updateNum>0){
                    findDynamicElasticsearch.subtractionLikeNumber(findId);
                }
            }
            return new FindDynamicLikeVO().setType("REMOVE");
        }else{
            int num = findDynamicLikeDaoRedis.addFindDynamicLike(query);
            if(num==1){
                //修改
                int addNum=findDynamicInfoDao.findAddLikeNumber(findId);
                if(addNum>0){
                    findDynamicElasticsearch.addFindDynamicLikeNumber(findId);
                }
            }
            integralRewardsAndPunishmentsHandler.signleDynamicPointPraisOver20(findId);
            return new FindDynamicLikeVO().setType("ADD");
        }

    }
}
